﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using SF.Base.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.SessionState;
using Nii.JSON;
using System.Collections;
using System.Text;
using System.Data;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

namespace SF.Dict.Web.Submit {
	/// <summary>
	/// $codebehindclassname$ 的摘要说明
	/// </summary>
	[WebService(Namespace = "http://tempuri.org/")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	public class submit : IHttpHandler, IRequiresSessionState {

		public void ProcessRequest(HttpContext context) {
			context.Response.ContentType = "text/plain";

			if (context.Request.UrlReferrer != null) {
				Logger.Detail(context.Request.UrlReferrer.ToString());
			}

			HttpRequest req = context.Request;
			HttpResponse resp = context.Response;

			string userid;
			string page = req.GetStr("page");
			string action = req.GetStr("action");

			string[] NotNeedLoginAction = new string[] { "003", "007", "013" };
			if (Global.DTUser == null) {
				if (!NotNeedLoginAction.Contains(action)) {
					context.Response.WriteRetJson(-160214);
					return;
				}
				userid = Guid.NewGuid().ToString();
			}
			else {
				userid = Global.DTUser.UserId;
			}

			//取出用户对象
			UserEntity user = Global.DTUser;

			if (action == "001") {
				#region 删除心得|评论
				int ret = CommentRules.Delete(context.Request.GetInt("cid"), Global.DTUser.UserId);
				if (ret < 0) {
					resp.WriteRetJson(ret);
				}
				else {
					resp.WriteRetJson(ret, "删除评论成功");
				}
				#endregion
			}
			else if (action == "002") {
				#region  屏蔽心得|评论
				int ret = CommentRules.Screen(context.Request.GetInt("cid"), Global.DTUser.UserId);
				if (ret < 0) {
					resp.WriteRetJson(ret);
				}
				else {
					resp.WriteRetJson(ret, "屏蔽评论成功");
				}
				#endregion
			}
			else if (action == "003") {
				#region 获取心得的评论
				int cid = req.GetInt("cid");

				CommentEntity comment = CommentRules.GetCommentByCid(cid);
				//判断心得是否存在
				if (comment == null) {
					resp.WriteRetJson(-160304);
				}

				List<CommentEntity> comments = CommentRules.GetChildCommentsByParentId(comment.CommentId, Global.DTUser.UserId);

				string output = JsonConvert.SerializeObject(comments);
				resp.WriteRetJson("0", "查询评论成功", output);
				#endregion
			}
			else if (action == "004") {
				#region 提交心得的评论

				string content = context.Server.UrlDecode(req.GetStr("cmt").Trim());	//获取评论内容

				if (content == "") {
					resp.WriteRetJson(-160306);
				}

				//截取250个字符
				if (content.Length() > 250) {
					content = content.SubString(250) + "[**]";
				}

				CommentEntity comment = CommentRules.GetCommentByCid(req.GetInt("cid"));

				if (comment == null) {
					resp.WriteRetJson(-160304);
				}

				//查询用户关于心得的全部评论
				List<CommentEntity> comments = CommentRules.GetUserChildCommentsByParentId(comment.CommentId, Global.DTUser.UserId);
				if (comments.Count > 0 && string.Equals(comments.First().Content, content, StringComparison.OrdinalIgnoreCase)) {
					resp.WriteRetJson(-160305);
				}

				CommentEntity ComObj = new CommentEntity();

				ComObj.Content = content;
				ComObj.CommentType = "replay";
				ComObj.CommentDate = DateTime.Now;
				ComObj.Agent = req.Browser.Browser + " " + req.Browser.Version;
				ComObj.Author = user.NiceName;
				ComObj.Email = user.Email;
				ComObj.Author = user.UserMeta["PROFILEIMAGEURL"];
				ComObj.UserId = user.UserId;
				ComObj.UID = user.UID;
				ComObj.ObjectType = comment.ObjectType;
				ComObj.ParentId = comment.CommentId;
				ComObj.ObjectId = comment.ObjectId;
				ComObj.IP = UtilHelper.GetRealIP();
				ComObj.Status = 1;
				ComObj.Approved = 1;
				ComObj.CommentId = Guid.NewGuid().ToString();

				int ret = CommentRules.Insert(ComObj);

				ComObj.CID = ret;

				if (ret >= 0) {
					resp.WriteRetJson("0", "发布评论成功", JsonConvert.SerializeObject(ComObj));
				}
				else {
					resp.WriteRetJson(ret);
				}

				#endregion
			}
			else if (action == "005") {
				#region 认识单词

				int did = req.GetInt("did");
				DictEntity dict = DictRules.GetDictByDidFromCache(did);

				if (dict == null) {
					resp.WriteRetJson(-160501);
				}
				int ret = DictRules.Know(Global.DTUser.UserId, dict.DictId);

				if (ret >= 0) {
					resp.WriteRetJson("0", "认识操作成功");
				}
				else {
					resp.WriteRetJson(ret);
				}

				#endregion
			}
			else if (action == "006") {
				#region 收藏单词

				int did = req.GetInt("did");

				DictEntity dict = DictRules.GetDictByDidFromCache(did);

				if (dict == null) {
					resp.WriteRetJson(-160501);
				}
				int ret = DictRules.Collect(Global.DTUser.UserId, dict.DictId);

				if (ret >= 0) {
					resp.WriteRetJson("0", "收藏操作成功");
				}
				else {
					resp.WriteRetJson(ret);
				}

				#endregion
			}
			else if (action == "007") {
				#region 获取心得
				int did = req.GetInt("did");

				//判断单词是否存在
				DictEntity dt = DictRules.GetDictByDidFromCache(did);
				if (dt == null) {
					resp.WriteRetJson(-160501);
				}

				//取评论的总条数
				int count = CommentRules.GetFirstLevelCommentsCountByObjectId(dt.DictId, "comment", userid);

				//取前3条评论
				List<CommentEntity> comments = CommentRules.GetFirstLevelCommentsByObjectId(dt.DictId, "comment", userid, 3);

				resp.WriteRetJson(count.ToString(), "查询心得成功", JsonConvert.SerializeObject(comments));
				#endregion
			}
			else if (action == "008") {
				#region 提交心得
				string content = context.Server.UrlDecode(req.GetStr("cmt").Trim());	//获取评论内容
				int did = context.Request.GetInt("did");

				//如果心得为空直接返回
				if (string.IsNullOrEmpty(content)) {
					resp.WriteRetJson(-160306);
				}

				//判断单词是否存在
				DictEntity dict = DictRules.GetDictByDidFromCache(did);
				if (dict == null) {
					resp.WriteRetJson(-160501);
				}

				//截取250个字符
				if (content.Length() > 250) {
					content = content.SubString(250) + "[**]";
				}

				//判断是否在最近3条中有重复
				List<CommentEntity> Comments = CommentRules.GetFirstLevelCommentsByObjectId(dict.DictId);

				int count1 = 0;
				Boolean exsist = false;
				foreach (CommentEntity dt1 in Comments) {
					if (count1 == 3) {
						break;
					}
					if (string.Equals(dt1.Content, content, StringComparison.OrdinalIgnoreCase)) {
						exsist = true;
						break;
					}
					count1++;
				}
				if (exsist == true) {
					resp.WriteRetJson(-160307);
				}

				CommentEntity ComObj1 = new CommentEntity();


				ComObj1.Content = content;
				ComObj1.CommentType = "comment";
				ComObj1.CommentDate = DateTime.Now;
				ComObj1.Agent = req.Browser.Browser + " " + req.Browser.Version;
				ComObj1.Author = user.NiceName;
				ComObj1.Email = user.Email;
				ComObj1.Avatar = user.UserMeta["Avatar"];
				ComObj1.UserId = user.UserId;
				ComObj1.UID = user.UID;
				ComObj1.ObjectType = ObjectType.Dict;
				ComObj1.ParentId = Guid.Empty.ToString();
				ComObj1.ObjectId = dict.DictId;
				ComObj1.IP = UtilHelper.GetRealIP();
				ComObj1.Status = 1;
				ComObj1.Approved = 1;
				ComObj1.CommentId = Guid.NewGuid().ToString();

				int ret = CommentRules.Insert(ComObj1);

				ComObj1.CID = ret;

				if (ret >= 0) {
					resp.WriteRetJson("0", "发布心得成功", JsonConvert.SerializeObject(ComObj1));
				}
				else {
					resp.WriteRetJson(ret);
				}
				#endregion
			}
			else if (action == "009") {
				#region 提交用户设置
				string json = context.Request.GetStream();

				IDictionary idict = JsonFacade.fromJSON(json);

				#region 参数验证


				#endregion




				//昵称不能为空
				if (idict["ac"] == null) {
					resp.WriteRetJson(-160215);
				}
				string nicename = idict["ac"].ToString();			//昵称
				if (string.IsNullOrEmpty(nicename)) {
					resp.WriteRetJson(-160215);
				}

				if (nicename != user.NiceName) {
					//判断昵称是否存在
					int ret = UserRules.GetUserIdByNiceName(nicename);
					if (ret == 0) {
						//不存在
						int ret1 = UserRules.UpdateNiceName(nicename, user.UID);
						if (ret1 < 0) {
							resp.WriteRetJson(ret1);
						}
					}
					else if (ret < 0) {
						resp.WriteRetJson(ret);
					}
				}

				StringDictionary sd = new StringDictionary();

				//性别
				if (idict["sex"] != null
				&& !string.IsNullOrEmpty(idict["sex"].ToString())
				&& (idict["sex"].ToString() == "男人" || idict["sex"].ToString() == "女人")) {
					sd.Add("sex", idict["sex"].ToString());
				}
				//生日
				if (idict["birthday"] != null
				&& !string.IsNullOrEmpty(idict["birthday"].ToString())
				&& RegexHelper.IsDate(idict["birthday"].ToString())) {
					sd.Add("birthday", idict["birthday"].ToString());
				}
				//身份
				if (idict["station"] != null
				&& !string.IsNullOrEmpty(idict["station"].ToString())
				&& (idict["station"].ToString() == "老年人"
					|| idict["station"].ToString() == "上班族"
					|| idict["station"].ToString() == "学生"
					|| idict["station"].ToString() == "小朋友")) {
					sd.Add("station", idict["station"].ToString());
				}
				//qq号
				if (idict["qq"] != null
				&& !string.IsNullOrEmpty(idict["qq"].ToString())
					//&& RegexHelper.IsQQ(idict["qq"].ToString())
				) {
					sd.Add("qq", idict["qq"].ToString());
				}
				//新浪微博
				if (idict["sinaweibo"] != null
				&& !string.IsNullOrEmpty(idict["sinaweibo"].ToString())
					//&& (user.USERMETA["sinaweibo"].StartsWith("http://weibo.com")
					//    || user.USERMETA["sinaweibo"].StartsWith("weibo.com")
					//    || user.USERMETA["sinaweibo"].StartsWith("www.weibo.com")
					//    || user.USERMETA["sinaweibo"].StartsWith("http://www.weibo.com")
					//    || user.USERMETA["sinaweibo"].StartsWith("t.sina.com")
					//    || user.USERMETA["sinaweibo"].StartsWith("http://t.sina.com"))
					) {
					sd.Add("sinaweibo", idict["sinaweibo"].ToString());
				}
				//人人网
				if (idict["renren"] != null
				&& !string.IsNullOrEmpty(idict["renren"].ToString())
					//&& Regex.IsMatch(idict["douban"].ToString(), @"^(https?://)?(www\\.)?((renren)|(xiaonei))\\.(com)/$")
				) {
					sd.Add("renren", idict["renren"].ToString());
				}
				//腾讯微博
				if (idict["qqweibo"] != null
				&& !string.IsNullOrEmpty(idict["qqweibo"].ToString())
					//&& (user.USERMETA["qqweibo"].StartsWith("http://t.qq.com/")
					//    || user.USERMETA["qqweibo"].StartsWith("t.qq.com/"))
					) {
					sd.Add("qqweibo", idict["qqweibo"].ToString());
				}
				//豆瓣
				if (idict["douban"] != null
				&& !string.IsNullOrEmpty(idict["douban"].ToString())
					//&& Regex.IsMatch(idict["douban"].ToString(),@"^(https?://)?(www\\.)?douban\\.com/$")
				) {
					sd.Add("douban", idict["douban"].ToString());
				}
				//MSN
				if (idict["msn"] != null
				&& !string.IsNullOrEmpty(idict["msn"].ToString())
					//&& RegexHelper.IsEmail(idict["msn"].ToString())
				) {
					sd.Add("msn", idict["msn"].ToString());
				}
				//QQ空间
				if (idict["qzone"] != null
				&& !string.IsNullOrEmpty(idict["qzone"].ToString())
					//&& idict["qzone"].ToString().IndexOf("qzone.qq.com") != -1
				) {
					sd.Add("qzone", idict["qzone"].ToString());
				}

				//一句话介绍
				if (idict["intro"] != null && !string.IsNullOrEmpty(idict["intro"].ToString())) {
					sd.Add("intro", idict["intro"].ToString());
				}

				int ret2 = MetaRules.AddUserMeta(user.UserId, sd);
				if (ret2 < 0) {
					resp.WriteRetJson(ret2);
				}

				resp.WriteRetJson("0", "保存成功");

				#endregion
			}
			else if (action == "010") {
				#region 修改登录邮箱

				string pwd = req.GetStr("pwd");
				string email = req.GetStr("email");

				if (!RegexHelper.IsEmail(email)) {
					resp.WriteRetJson(-160222);
				}

				//密码正确
				if (pwd == user.Pass) {
					int ret = UserRules.UpdateLogin(email, user.UID, pwd);
					if (ret == 1) {
						user.Login = email;
						resp.WriteRetJson("0", "更改成功");
					}
					else {
						resp.WriteRetJson(ret);
					}
				}
				else {
					resp.WriteRetJson(-160220);
				}

				#endregion
			}
			else if (action == "011") {
				#region 修改登录邮箱

				string pwd = req.GetStr("pwd");
				string npwd = req.GetStr("npwd");

				if (string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(npwd)) {
					resp.WriteRetJson(-160223);
				}

				//密码正确
				if (pwd == user.Pass) {
					int ret = UserRules.UpdatePass(npwd, user.UID, pwd);
					if (ret == 1) {
						user.Pass = npwd;
						resp.WriteRetJson("0", "更改成功");
					}
					else {
						resp.WriteRetJson(ret);
					}
				}
				else {
					resp.WriteRetJson(-160224);
				}

				#endregion
			}
			else if (action == "012") {
				#region 关注词汇表

				int vid = req.GetInt("vid");

				//判断词汇表是否存在
				VocabularyEntity dt = VocabularyRules.GetVocabulary(vid);
				if (dt == null) {
					resp.WriteRetJson(-160105, "");
				}

				int ret = VocabularyRules.Follow(user.UserId, dt.VocabularyId);

				resp.WriteRetJson(ret);

				#endregion
			}
			else if (action == "013") {
				#region 提交意见建议
				string Content = context.Server.UrlDecode(req.GetStr("cmt").Trim());	//获取评论内容
				string UserId = Guid.Empty.ToString();
				if (user != null) {
					UserId = user.UserId;
				}
				int ret = AdviseRules.Advise(UserId, Content);

				resp.WriteRetJson(ret);

				#endregion
			}
			else if (action == "014") {
				#region 关注单词

				int did = req.GetInt("did");

				//判断词汇表是否存在
				DictEntity dt = DictRules.GetDictByDidFromCache(did);
				if (dt == null) {
					resp.WriteRetJson(-160105, "");
				}

				int ret = DictRules.Collect(user.UserId, dt.DictId);

				resp.WriteRetJson(ret);

				#endregion
			}
			else if (action == "015") {
				#region 创建词汇表

				string Name = req.GetStr("name");
				string Desc = req.GetStr("desc");
				string Dists = req.GetStr("dicts").Replace("，", ",");
				int Sid = req.GetInt("sid", -1);
				if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Dists)) {
					resp.WriteRetJson(-1);
				}

				StationEntity Station = VocabularyRules.GetVocabularyStation(Sid);
				string StationId = string.Empty;
				if (Station == null) {
					StationId = "EBC64D03-0568-46A6-9BA6-2BC92EFE2F31";
				}
				else {
					StationId = Station.StationId;
				}

				VocabularyEntity Vocabulary = new VocabularyEntity();
				Vocabulary.Name = Name;
				Vocabulary.Slug = "";
				Vocabulary.UserId = userid;
				Vocabulary.VocabularyId = Guid.NewGuid().ToString();
				Vocabulary.Description = Desc;
				Vocabulary.Status = -2;	//为提醒创建者给每个单词添加解释
				Vocabulary.ParentId = StationId;
				string[] ADist = Regex.Split(Dists, ",");

				List<DictEntity> DictList = new List<DictEntity>();

				for (int i = 0; i < ADist.Length; i++) {
					DictEntity d = new DictEntity();
					if (ADist[i].Trim() == "") {
						continue;
					}
					d.ASpell = ADist[i];
					d.DictId = Guid.NewGuid().ToString();
					DictList.Add(d);
				}
				Vocabulary.DictList = DictList;

				int ret = VocabularyRules.Insert(Vocabulary);
				if (ret >= 0) {
					resp.WriteRetJson(0, Vocabulary.Vid.ToString());
				}
				else {
					resp.WriteRetJson(ret);
				}

				#endregion
			}
			else if (action == "016") {
				#region 获取可导入的词汇表

				long Vid = req.GetLong("vid");

				VocabularyEntity Vocabulary = VocabularyRules.GetVocabulary(Vid);
				List<VocabularyEntity> SpecialVocabularys = new List<VocabularyEntity>();
				if (!string.IsNullOrEmpty(Vocabulary.StationId)) {
					SpecialVocabularys = VocabularyRules.GetSpecialVocabularysByStationId(Vocabulary.StationId);
				}

				if (SpecialVocabularys.Count == 0) {
					SpecialVocabularys = VocabularyRules.GetVocabularysByVocabularyIds("'E60175F3-22A4-4005-AF75-543F39DCA99F','AC0ADDF9-A663-45EC-B047-D7A4D7F25AC9','F41DF055-CA47-4DA2-886C-F9B76C197DDF'");
				}

				resp.WriteRetJson(SpecialVocabularys.Count.ToString(), "查询成功", JsonConvert.SerializeObject(SpecialVocabularys));

				#endregion
			}
			else if (action == "017") {
				#region 给自建词汇表导入解释

				long Vid = req.GetLong("vid");
				long FVid = req.GetLong("fvid");

				VocabularyEntity Vocabulary = VocabularyRules.GetVocabulary(Vid);
				VocabularyEntity FromVocabulary = VocabularyRules.GetVocabulary(FVid);
				if (Vocabulary == null || FromVocabulary == null) {
					resp.WriteRetJson(-1);
				}

				int ret = VocabularyRules.InportParaphrase(Vocabulary.VocabularyId, FromVocabulary.VocabularyId);

				resp.WriteRetJson(ret);
				#endregion
			}
			else if (action == "018") {
				#region 编辑词汇表
				string Name = req.GetStr("name");
				string Desc = req.GetStr("desc");
				string Dists = req.GetStr("dicts").Replace("，", ",").Replace("\r\n", ",").Replace("\r", ",").Replace("\n", ",");
				Logger.Detail(Dists);
				long Vid = req.GetLong("vid");
				int Sid = req.GetInt("sid", -1);

				if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Dists)) {
					resp.WriteRetJson(-1);
				}

				VocabularyEntity Vocabulary = VocabularyRules.GetVocabulary(Vid);

				if (Vocabulary == null) {
					resp.WriteRetJson(-1);
				}

				StationEntity Station = VocabularyRules.GetVocabularyStation(Sid);
				string StationId = string.Empty;
				if (Station == null) {
					StationId = "EBC64D03-0568-46A6-9BA6-2BC92EFE2F31";
				}
				else {
					StationId = Station.StationId;
				}

				Vocabulary.Name = Name;
				Vocabulary.Slug = "";
				Vocabulary.Description = Desc;
				Vocabulary.Status = -1;	//为提醒创建者给每个单词添加解释
				Vocabulary.ParentId = StationId;
				string[] ADist = Regex.Split(Dists, ",");

				Vocabulary.DictList = DictRules.GetDictsByVid(Vocabulary.VocabularyId);

				List<DictEntity> DictList = Vocabulary.DictList;

				//选出新增的单词
				for (int i = 0; i < ADist.Length; i++) {
					DictEntity Dict = new DictEntity();
					if (ADist[i].Trim() == "") {
						continue;
					}
					Dict.ASpell = ADist[i];

					Boolean Exist = false;
					foreach (DictEntity d in DictList) {
						if (d.ASpell == Dict.ASpell) {
							Exist = true;	//存在
							d.EditType = "update";
							d.RelationOrder = i;
							break;
						}
					}

					if (Exist == false) {
						//如果不存在
						Dict.DictId = Guid.NewGuid().ToString();
						Dict.RelationOrder = i;
						Dict.EditType = "insert";
						DictList.Add(Dict);
					}
				}

				//选择被删除的单词
				foreach (DictEntity d in DictList) {
					Boolean Exist = false;
					for (int i = 0; i < ADist.Length; i++) {
						if (ADist[i].Trim() == "") {
							continue;
						}
						if (d.ASpell == ADist[i]) {
							Exist = true; //存在
							break;
						}
					}
					if (Exist == false) {
						//不存在
						d.EditType = "delete";
					}
				}

				int ret = VocabularyRules.Edit(Vocabulary);
				if (ret >= 0) {
					resp.WriteRetJson(0, Vocabulary.Vid.ToString());
				}
				else {
					resp.WriteRetJson(ret);
				}
				#endregion
			}
			else if (action == "019") {
				#region 获取相关单词的解释
				long Did = req.GetLong("did");
				DictEntity Dict = DictRules.GetDict(Did);
				if (Dict == null) {
					resp.WriteRetJson(-1);
				}
				List<DictEntity> Dicts = DictRules.GetRelationDictsByDictId(Did);

				resp.WriteRetJson(Dicts.Count.ToString(), "查询成功", JsonConvert.SerializeObject(Dicts));
				#endregion
			}
			else if (action == "020") {
				#region 修改单词解释
				string Paraphrase = req.GetStr("ph");
				string Commentate = req.GetStr("ct");
				long Did = req.GetLong("did");

				DictEntity Dict = DictRules.GetDict(Did);
				if (Dict == null) {
					resp.WriteRetJson(-1);
				}

				if (Paraphrase == Dict.Paraphrase && Commentate == Dict.Commentate) {
					resp.WriteRetJson(0);
				}

				int ret = DictRules.UpdateParaphrase(Dict, Paraphrase, Commentate, user.UserId);

				resp.WriteRetJson(ret);

				#endregion
			}
			else {
				resp.WriteRetJson(-160601);
			}
		}

		public bool IsReusable {
			get {
				return false;
			}
		}
	}
}

